package 多线程初阶.示例测试;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 实现一个线程池
 */
class MyThreadPool {
    private BlockingQueue<Runnable> queue=new LinkedBlockingDeque<>();
    public void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public MyThreadPool(int count){
        for (int i = 0; i < count; i++) {
            Thread thread=new Thread(()->{
                while (!Thread.currentThread().isInterrupted()){
                    try {
                        queue.take().run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            });
            thread.start();
        }
    }
}
public class TestDemo24 {
    private static volatile int count=0;
    public static void main(String[] args) {
        MyThreadPool pool=new MyThreadPool(5);
        while (true){
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(++count);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
